<div class="layuimini-container layuimini-page-anim" >
    <div class="layuimini-main" >
        <fieldset class="table-search-fieldset" >
            <legend>搜索指令</legend>
            <div style="margin-bottom:5px">
                <form class="layui-form layui-form-pane" id="sform">
                        <div class="layui-inline">
                            <label class="layui-form-label">指令名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="cmd_name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
						<div class="layui-inline">
                            <label class="layui-form-label">设备地址</label>
                            <div class="layui-input-inline">
                                <input type="text" name="slaveid" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <!--<div class="layui-inline">
                            <label class="layui-form-label">型号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="model" autocomplete="off" class="layui-input">
                            </div>
                        </div>-->
                        <div class="layui-inline">
                            <label class="layui-form-label">指令描述</label>
                            <div class="layui-input-inline">
                                <input type="text" name="desc" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary layui-btn-sm"  lay-submit id="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                </form>
            </div>
        </fieldset>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container"><div class="layui-btn-group" stylex="margin-top:-5px;padding:0px">
                <button class="layui-btn  layui-btn-sm layui-btn-primary" lay-event="add-MB-RTU-POLL" data-type="MB-RTU-POLL" name="addCMDBtn" > 新建 MB RTU POLL</button>
                <button class="layui-btn  layui-btn-sm layui-btn-primary" lay-event="add-MB-TCP-POLL" data-type="MB-TCP-POLL" name="addCMDBtn"  > 新建 MB TCP POLL </button>
                <button class="layui-btn  layui-btn-sm layui-btn-primary" lay-event="add-CAN-NODE" data-type="CAN-NODE" name="addCMDBtn"  > 新建 CAN NODE </button>
                <button class="layui-btn layui-btn-sm layui-btn-primary  " lay-event="add-OTHER" data-type="OTHER"> 添加其他设备 </button>
</div><div class="layui-btn-group">
                <button class="layui-btn layui-btn-sm layui-btn-danger layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
				<button class="layui-btn layui-btn-sm layui-btn-normal " id="refershbtn" lay-event="refersh"> 刷新 </button>
 </div>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<script type="text/html" id="idTpl">
  <a class="layui-table-link">{{ d.cmd_name }}</a>
</script>
<script>
 
    layui.use(['form', 'table','miniPage','element'], function () {
        var $ = layui.jquery,
            form = layui.form, 
            table = layui.table,
			element = layui.element,
            miniPage = layui.miniPage;
		var tdata =[];

		table.render({
				elem: '#currentTableId',
				//url: '/xapi/command',
				data: tdata,
				toolbar: '#toolbarDemo',
				height: 'full-255', 
				cellMinWidth: 80,
				defaultToolbar: ['filter', 'exports', 'print', {
					title: '提示',
					layEvent: 'LAYTABLE_TIPS',
					icon: 'layui-icon-tips'
				}]
				,parseData:function (res){
					return {
						"code":0,
						"data":res
					}
				},
				cols: [[
					{type: "checkbox"},
					{field: 'cmd_name', title: '指令名称',width: 200,  edit: 'text', sort: true},
					{field: 'port', title: '端口',width: 120, sort: true ,templet:function (dat){
								return dat["port_name"]+"("+dat["port_type"]+ ")";
							},},{field: 'type', title: '类型',width: 140, sort: true },
					{field: 'slaveid',  title: '从机地址',  width: 90, sort: true },
					{field: 'funcCode', title: '功能',width: 80, sort: true },
					{field: 'address', title: '寄存器地址',width: 100 },
					{field: 'quantity', title: '个数' ,width: 100},
					
					//{field: 'name', title: '设备名称',width: 200,  sort: true },, templet: '#idTpl'
				   // {field: 'model',  title: '型号', width: 200,sort: true , sort: true },
					{field: 'parser_rules',  title: '数据处理',templet:function (dat){
										var rules= dat["parser_rules"];
										//if (rules)return rules.join("");
										var s="";
										if ( rules==null ) return "";
										for (var i=0;i<rules.length;i++){
											s+= rules[i]["id"] + ':' +rules[i]["name"]+"(" + rules[i]["numtype"]+")"+";";
										}
										return s;
							},},
					{field: 'desc',  title: '描述',edit: 'text'}
					//,{fixed: 'right', title:'操作', toolbar: '#currentTableBar', width:150}
				]], 
				limits: [10, 15, 20, 25, 50, 100],
				limit: 15,
				id:'currentTableId',
				page: true,
				even: false,
				skin: 'line,row'
			});

		function loadCmdData(){
				$.ajax({
						async: false,
						type: "GET",
						url: '/xapi/command',
						success: function (map) {
							var cmds=[];
							for (var key in map) {
								cmds.push(map[key]);
							}
							tdata=cmds;		
							table.reload("currentTableId",{"elem":"#currentTableId",data:tdata});
						}
				});
		}
 
		
		$("#refershbtn").click(function(obj){
			loadCmdData();
		 });

		loadCmdData();
		//监听行单击事件（双击事件为：rowDouble）
		/**/table.on('rowDouble(currentTableFilter)', function(obj){
			var data = obj.data;
			layer.alert(JSON.stringify(data.id), {
			  title: '当前行数据：'
			});
			//标注选中样式
			obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
			var content = miniPage.getHrefContent('/page/command/edit.html');
			var index = layer.open({
						title: '编辑设备',
						type: 1,
						shade: 0.3,
						maxmin:true,
						shadeClose: true,
						area:['1200px','600px'],
						content: content,
					}); 
		  });
		  
        // 监听搜索操作
		$("#data-search-btn").click(function(obj){
			var serchkeys=$("#sform").serializeArray();
 			//console.log(serchkeys);
			var newdata = tdata.filter(function(p){
					var rc=0;
					for (var i=0;i<serchkeys.length;i++){
						if (serchkeys[i]["value"]!="" ){
							return p[serchkeys[i]["name"]].indexOf( serchkeys[i]["value"])>-1;
						}else{
							rc++;
						}
					}
					if (rc==serchkeys.length){
						return p;
					}
			});
            table.reload('currentTableId', {
				data:newdata,
				page: {
                    curr: 1
                }            
            });
            return false;
        });

		
		//$("button[name='addCMDBtn']").click(function(obj){
			//console.log( $(obj.target).attr("data-type"));
	    function NewCMD(x){
			var cmdtype=x;//$(obj.target).attr("data-type");			
			var content = miniPage.getHrefContent('/page/command/'+cmdtype+'.html?_='+new Date());
			var openWH = miniPage.getOpenWidthHeight();
			var index = layer.open({
						title: '新建 '+cmdtype.replace("add-",""),
						type: 1,
						shade: 0.3,
						maxmin:false,
						shadeClose: false,
						fixed: true,  resize: false,
						area:['auto'],
						content: content,
			});
			$("#type").val(cmdtype.replace("add-",""));
		}
		//});

        /**
         * toolbar事件监听
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
			//console.log(obj.event );
			
            /*if (obj.event === 'addcmd') {   // 监听添加操作
               
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }*/
			var checkStatus = table.checkStatus(obj.config.id);
			switch(obj.event){
			  case 'refersh':
			  loadCmdData();
			  break;
			 
			  NewCMD
			  case 'delete':
				var data = checkStatus.data;
				if(data.length ==0){
					layer.msg('请选择需要删除的指令.');
					return ;
				}
				layer.confirm('确认删除？', function(index) {
					layer.close(index);
                    $.ajax({
						async: false,
						type: "DELETE",
						url: '/xapi/command',
						data: JSON.stringify(data),
						headers : {'Content-Type' : 'application/json;charset=utf-8'}, 
						success: function (data) {
								 if (data.code === 0) {
									loadCmdData();
									/*layer.msg("删除成功.", {
										icon: 2,
										msg:data.desc
									});*/
								}else{
									layer.msg("删除出错.", {
										icon: 2,
										msg:data.desc
									});
								}
							}
						});
                });
			  break;
			  
			  //自定义头工具栏右侧图标 - 提示
			  case 'LAYTABLE_TIPS':
				layer.alert('这是工具栏右侧自定义的一个图标按钮');
			  break;

			  default:
			    if  (obj.event.startsWith('add-')){
				NewCMD( obj.event);
				}
			  break;

			};
        });

        //监听表格复选框选择
        /*table.on('checkbox(currentTableFilter)', function (obj) {
           
        });
		
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {

                var content = miniPage.getHrefContent('page/protocol/add.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '编辑指令',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area:['800px','600px'],
                    content: content,
                }); 
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确定删除么', function (index) {
                    obj.del();
                    layer.close(index);
                });
            }
        });*/

    });
</script>